package com.zmh.arithmetic.linked_list;

import java.util.HashSet;
import java.util.Set;

/**
 * 判断链表中环
 *
 * @author zmh
 * @create 2018-11-20 上午10:40
 **/
public class LinkedListCycle {
    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) { val = x; }
    }

    public boolean hasCycleByHash(ListNode head) {
        Set<ListNode> nodeSet = new HashSet<>();
        while (null != head) {
            if (nodeSet.contains(head)) {
                return true;
            } else {
                nodeSet.add(head);
                head = head.next;
            }
        }

        return false;
    }

    public boolean hasCycleByTwoPoints(ListNode head) {
        if (null == head || null == head.next) {
            return false;
        }
        ListNode one = head;
        ListNode two = head.next;
        while (null != two && null != two.next) {
            if (one != two) {
                two = two.next.next;
                one = one.next;
                continue;
            } else {
                return true;
            }
        }
        return false;
    }

    public boolean hasCycleByTwoPoints_perfect(ListNode head) {
        if (null == head || null == head.next) {
            return false;
        }
        ListNode one = head;
        ListNode two = head.next;
        while (one != two) {
            if (null == two || null == two.next) {
                return false;
            }
            one = one.next;
            two = two.next.next;
        }
        return true;
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        listNode.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;
        listNode5.next = listNode3;
        LinkedListCycle reverseLinkedList = new LinkedListCycle();
        boolean result = reverseLinkedList.hasCycleByTwoPoints_perfect(listNode);
        System.out.println(result);
    }
}
